<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>个人课表</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
  <style>
    body {
      font-family: 'Microsoft YaHei', Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f5f5f5;
      color: #333;
    }

    .header {
      background-color: #0078d7;
      color: white;
      padding: 10px 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .logo {
      display: flex;
      align-items: center;
    }

    .logo-text {
      font-size: 22px;
      font-weight: normal;
    }

    .nav-bar {
      background-color: #f0f0f0;
      padding: 0 20px;
      border-bottom: 1px solid #ddd;
    }

    .nav-menu {
      list-style-type: none;
      margin: 0;
      padding: 0;
      display: flex;
    }

    .nav-menu li {
      position: relative;
    }

    .nav-menu a {
      display: block;
      padding: 15px;
      text-decoration: none;
      color: #333;
      transition: background-color 0.3s;
    }

    .nav-menu a:hover {
      background-color: #e0e0e0;
    }

    .schedule-container {
      max-width: 1200px;
      margin: 20px auto;
      padding: 20px;
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

    .schedule-header {
      text-align: center;
      margin-bottom: 30px;
      border-bottom: 1px solid #eee;
      padding-bottom: 15px;
    }

    .schedule-table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
    }

    .schedule-table th,
    .schedule-table td {
      border: 1px solid #ddd;
      padding: 12px;
      text-align: center;
    }

    .schedule-table th {
      background-color: #f8f9fa;
      font-weight: bold;
    }

    .schedule-table td {
      height: 100px;
      vertical-align: top;
    }

    .course-cell {
      background-color: #e3f2fd;
      border-radius: 4px;
      padding: 8px;
      margin: 2px;
      font-size: 14px;
    }

    .course-name {
      font-weight: bold;
      margin-bottom: 4px;
    }

    .course-info {
      font-size: 12px;
      color: #666;
    }

    .time-slot {
      background-color: #f8f9fa;
      font-weight: bold;
    }
  </style>
</head>

<body>
  <!-- 顶部导航栏 -->
  <div class="header">
    <div class="logo">
      <h1 class="logo-text">教学管理信息服务平台</h1>
    </div>
  </div>

  <!-- 二级导航栏 -->
  <nav class="nav-bar">
    <ul class="nav-menu">
      <li><a href="student.html">首页</a></li>
    </ul>
  </nav>

  <div class="schedule-container">
    <div class="schedule-header">
      <h1>个人课表</h1>
    </div>
    <table class="schedule-table">
      <thead>
        <tr>
          <th>节次</th>
          <th>周日</th>
          <th>周一</th>
          <th>周二</th>
          <th>周三</th>
          <th>周四</th>
          <th>周五</th>
          <th>周六</th>
        </tr>
      </thead>
      <tbody id="scheduleBody">
        <!-- 课程表内容将通过JavaScript动态填充 -->
      </tbody>
    </table>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', async function () {
      // 检查登录状态
      const userToken = localStorage.getItem('userToken');
      if (!userToken) {
        alert('请先登录');
        window.location.href = 'index.html';
        return;
      }

      // 获取用户ID
      const userId = localStorage.getItem('user_id');
      if (!userId) {
        alert('未找到用户信息，请重新登录');
        window.location.href = 'index.html';
        return;
      }

      try {
        // 获取已选课程
        const response = await fetch(`/api/student/courses?user_id=${userId}`);
        const data = await response.json();

        if (!data.success) {
          throw new Error(data.message || '获取课程信息失败');
        }

        // 打印获取到的课程数据，以便调试
        console.log('获取到的课程数据:', data.courses);

        // 生成课表
        generateSchedule(data.courses);
      } catch (error) {
        console.error('加载课表失败:', error);
        alert('加载课表失败，请稍后重试');
      }
    });

    function generateSchedule(courses) {
      const scheduleBody = document.getElementById('scheduleBody');
      const timeSlots = [
        { time: '8:00-9:40', section: '第1-2节', backendSection: '第一大节' },
        { time: '10:00-11:40', section: '第3-4节', backendSection: '第二大节' },
        { time: '14:00-15:40', section: '第5-6节', backendSection: '第三大节' },
        { time: '16:00-17:40', section: '第7-8节', backendSection: '第四大节' },
        { time: '19:00-20:40', section: '第9-10节', backendSection: '第五大节' }
      ];

      const weekdaysOrder = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      const weekdaysMap = weekdaysOrder.reduce((acc, day, index) => { acc[day] = index; return acc; }, {});

      // 创建一个空的二维数组来存储按时间和日期组织的课程，确保每个单元格都是独立的数组实例
      const scheduleData = Array(timeSlots.length).fill(null).map(() => Array(weekdaysOrder.length).fill(null).map(() => []));

      // 将课程按日期和节次分组
      courses.forEach(course => {
        const weekdayIndex = weekdaysMap[course.weekday];
        const sectionIndex = timeSlots.findIndex(slot => slot.backendSection === course.section);

        // 确保索引有效
        if (weekdayIndex !== undefined && sectionIndex !== -1) {
          scheduleData[sectionIndex][weekdayIndex].push(course);
        } else {
          console.warn('发现无效的课程时间或节次:', course); // 添加警告日志
        }
      });

      // 创建课表行和单元格
      scheduleBody.innerHTML = ''; // 清空原有内容
      timeSlots.forEach((slot, sectionIndex) => {
        const row = document.createElement('tr');

        // 添加时间列
        const timeCell = document.createElement('td');
        timeCell.className = 'time-slot';
        timeCell.innerHTML = `${slot.section}<br>${slot.time}`;
        row.appendChild(timeCell);

        // 添加每天的课程单元格
        weekdaysOrder.forEach((weekday, weekdayIndex) => {
          const cell = document.createElement('td');

          // 获取该时间段的课程
          const dayCourses = scheduleData[sectionIndex][weekdayIndex];

          // 添加课程信息
          dayCourses.forEach(course => {
            const courseDiv = document.createElement('div');
            courseDiv.className = 'course-cell';
            courseDiv.innerHTML = `
              <div class="course-name">${course.course_name || ''}</div>
              <div class="course-info">
                ${course.teacher_real_name || course.teacher || ''}<br>
                ${course.classroom || ''}
              </div>
            `;
            cell.appendChild(courseDiv);
          });

          row.appendChild(cell);
        });

        scheduleBody.appendChild(row);
      });
    }
  </script>
</body>

</html>